<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="时间查询">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="单据编号" prop="billNumber">
        <el-input
          v-model="queryParams.billNumber"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户姓名" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="团队查询" prop="deptId">
        <treeselect style="width: 215px" v-model="queryParams.deptId" :options="deptOptions" :show-count="true"
                    placeholder="请选择团队"/>
      </el-form-item>
      <el-form-item label="是否审核" prop="examStatus">
        <el-select v-model="queryParams.examStatus" placeholder="请选择是否审核" clearable>
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['data:sale:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['data:sale:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['data:sale:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['data:sale:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table stripe border v-loading="loading" :data="saleList" @selection-change="handleSelectionChange"
              @sort-change="tableSortChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键" align="center" prop="id" v-if="false"/>
      <el-table-column label="单据编号" align="center" prop="billNumber"/>
      <el-table-column label="提报人" align="center" prop="nickName"/>
      <el-table-column label="上级姓名" align="center" prop="stockNickName"/>
      <el-table-column label="总金豆" align="center" prop="allGold"/>
      <el-table-column label="增加名额" align="center" prop="addUser"/>
      <el-table-column label="总数量" align="center" prop="allAmount"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="primary"
            plain
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['data:sale:edit']"
          >修改
          </el-button>
          <el-button
            size="small"
            type="danger"
            plain
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['data:sale:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-row :gutter="15">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="单据编号" prop="billNumber">
                <el-input v-model="form.billNumber" placeholder="单据编号自动生成" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报货人" prop="nickName">
                <el-input placeholder="请选择报货人" v-model="form.nickName" readonly
                          class="input-with-select">
                  <el-button slot="append" icon="el-icon-search" @click="showUserList"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上级姓名" prop="stockNickName">
                <el-input v-model="form.stockNickName" placeholder="请选择上级姓名" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="总金豆" prop="allGold">
                <el-input v-model="form.allGold" placeholder="自动计算" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="增加名额" prop="addUser">
                <el-input v-model="form.addUser" placeholder="自动计算" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="总数量" prop="allAmount">
                <el-input v-model="form.allAmount" placeholder="自动计算" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input :rows="4" v-model="form.remark" type="textarea" placeholder="请输入备注"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-divider content-position="center">订单明细信息</el-divider>
            </el-col>
          </el-row>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button v-if="form.examStatus == 'N'" type="primary" icon="el-icon-plus" size="mini"
                         @click="showGoodList">添加
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-if="form.examStatus == 'N'" type="danger" icon="el-icon-delete" size="mini"
                         @click="handleDeleteDataSaleItem">删除
              </el-button>
            </el-col>
          </el-row>
          <el-table :data="dataSaleItemList" :row-class-name="rowDataSaleItemIndex"
                    @selection-change="handleDataSaleItemSelectionChange" ref="dataSaleItem" show-summary>
            <el-table-column type="selection" width="80" align="center"/>
            <el-table-column label="序号" align="center" prop="index" width="50"/>
            <el-table-column label="商品代码" prop="goodCode" width="150"/>
            <el-table-column label="商品名称" prop="goodName" width="auto"/>
            <el-table-column label="金豆数量" prop="goldAmount" width="150"/>
            <el-table-column label="商品数量" prop="goodAmount" width="150"/>
          </el-table>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="form.examStatus == 'N'">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 会员列表 -->
    <el-dialog title="会员列表" :visible.sync="userOpen" width="800px" append-to-body>
      <el-form :model="queryUserParams" ref="queryUserForm" size="small" :inline="true"
               label-width="68px">
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            v-model="queryUserParams.phonenumber"
            placeholder="请输入手机号码"
            clearable
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="会员级别" prop="userLevel">
          <el-select
            v-model="queryUserParams.userLevel"
            placeholder="会员级别"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in dict.type.user_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleUserQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetUserQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table stripe border v-loading="userLoading" :data="userList">
        <el-table-column label="会员编号" align="center" key="userId" prop="userId"/>
        <el-table-column label="登录账号" align="center" key="userName" prop="userName"
                         :show-overflow-tooltip="true"/>
        <el-table-column label="会员姓名" align="center" key="nickName" prop="nickName"
                         :show-overflow-tooltip="true"/>
        <el-table-column label="报货人" align="center" key="stockNickName" prop="stockNickName"
                         :show-overflow-tooltip="true"/>
        <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber"
                         width="120"/>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="100"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              :disabled="scope.row.stockUserId == null"
              size="small"
              type="primary"
              plain
              icon="el-icon-edit"
              @click="selectUser(scope.row)"
              v-hasPermi="['data:sale:edit']"
            >选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="userTotal>0"
        :total="userTotal"
        :page.sync="queryUserParams.pageNum"
        :limit.sync="queryUserParams.pageSize"
        @pagination="getUserList"
      />
    </el-dialog>

    <!-- 商品列表 -->
    <el-dialog title="商品列表" :visible.sync="goodOpen" width="800px" append-to-body>
      <el-form :model="queryGoodParams" ref="queryGoodForm" size="small" :inline="true"
               label-width="68px">
        <el-form-item>
          <el-button type="error" icon="el-icon-delete" size="mini" @click="closeGood">关闭</el-button>
        </el-form-item>
      </el-form>
      <el-table stripe border v-loading="goodLoading" :data="goodList">
        <el-table-column label="商品主键" align="center" prop="id" v-if="false"/>
        <el-table-column label="商品图片" align="center" prop="goodImg" width="100">
          <template slot-scope="scope">
            <image-preview :src="scope.row.goodImg" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="商品代码" align="center" prop="goodCode"/>
        <el-table-column label="商品名称" align="center" prop="goodName"/>
        <el-table-column label="计量单位" align="center" prop="unitName"/>
        <el-table-column label="商品规格" align="center" prop="standard"/>
        <el-table-column label="金豆个数" align="center" prop="goldBean"/>
        <el-table-column label="下单数量" align="center" min-width="100">
          <template slot-scope="scope">
            <el-input v-model="scope.row.goodAmount" placeholder="下单数量"/>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="100"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="small"
              type="primary"
              plain
              icon="el-icon-edit"
              @click="selectGood(scope.row)"
              v-hasPermi="['system:user:edit']"
            >添加
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="goodTotal>0"
        :total="goodTotal"
        :page.sync="queryGoodParams.pageNum"
        :limit.sync="queryGoodParams.pageSize"
        @pagination="getGoodList"
      />
    </el-dialog>
  </div>
</template>

<script>
import {addSale, delSale, getSale, listSale, updateSale} from "@/api/data/sale";
import {deptTreeSelect, listStockUser} from "@/api/system/user";
import {listGood} from "@/api/base/good";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {parseTime} from "@/utils/ruoyi";

export default {
  name: "Sale",
  dicts: ['sys_type', 'user_level', 'sys_yes_no'],
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedDataSaleItem: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单信息表格数据
      saleList: [],
      // 订单明细表格数据
      dataSaleItemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: undefined,
        isAsc: undefined,
        billNumber: null,
        deptId: null,
        userId: null,
        nickName: null,
        allGold: null,
        addUser: null,
        allAmount: null,
        examStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        nickName: [
          {required: true, message: "请选择会员", trigger: "blur"}
        ],
      },
      // 会员遮罩层
      userLoading: true,
      // 会员总条数
      userTotal: 0,
      // 会员表格数据
      userList: [],
      // 是否显示会员弹出层
      userOpen: false,
      // 会员查询参数
      queryUserParams: {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,
        phonenumber: undefined,
        userLevel: undefined
      },
      // 商品遮罩层
      goodLoading: true,
      // 商品总条数
      goodTotal: 0,
      // 商品表格数据
      goodList: [],
      // 是否显示商品弹出层
      goodOpen: false,
      // 商品查询参数
      queryGoodParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 代理树选项
      deptOptions: undefined,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近六个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 182);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一整年',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 日期范围
      dateRange: [parseTime(new Date().setDate(1), '{y}-{m}-{d}'), parseTime(new Date(), '{y}-{m}-{d}')],
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  methods: {
    /** 查询代理下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 显示会员列表 */
    showUserList() {
      this.resetUserQuery()
      this.userOpen = true
      this.getUserList()
    },
    /** 会员列表 */
    getUserList() {
      this.userLoading = true;
      listStockUser(this.queryUserParams).then(response => {
          this.userList = response.rows;
          this.userTotal = response.total;
          this.userLoading = false;
        }
      );
    },
    /** 搜索会员按钮操作 */
    handleUserQuery() {
      this.queryUserParams.pageNum = 1;
      this.userList = [];
      this.userTotal = 0;
      this.getUserList();
    },
    /** 重置会员按钮操作 */
    resetUserQuery() {
      this.resetForm("queryUserForm");
      this.handleUserQuery();
    },
    /** 选择会员 */
    selectUser(row) {
      if (row.stockUserId == null) {
        this.$modal.msgError("会员不存在下单人，不可选择");
        return
      }
      this.form.deptId = row.deptId
      this.form.userId = row.userId
      this.form.nickName = row.nickName
      this.form.stockUserId = row.stockUserId
      this.form.stockNickName = row.stockNickName
      this.userGold = row.goldAvailable
      this.userOpen = false
    },
    /** 显示商品列表 */
    showGoodList() {
      this.resetGoodQuery()
      this.goodOpen = true
      this.getGoodList()
    },
    /** 商品列表 */
    getGoodList() {
      this.goodLoading = true;
      listGood(this.queryGoodParams).then(response => {
          this.goodList = response.rows;
          this.goodTotal = response.total;
          this.goodLoading = false;
        }
      );
    },
    /** 搜索商品按钮操作 */
    handleGoodQuery() {
      this.queryGoodParams.pageNum = 1;
      this.goodList = [];
      this.goodTotal = 0;
      this.getGoodList();
    },
    /** 重置商品按钮操作 */
    resetGoodQuery() {
      this.resetForm("queryGoodForm");
      this.handleGoodQuery();
    },
    /** 选择商品 */
    selectGood(row) {
      if (row.goodAmount == undefined) {
        this.$modal.msgError("请输入下单数量");
        return
      }
      let exit = this.dataSaleItemList.find((item) => {
        return item.goodId === row.id
      })
      if (exit != undefined) {
        exit.goldAmount = row.goodAmount * row.goldBean
        exit.goodAmount = row.goodAmount
        return;
      }
      let obj = {};
      obj.goodId = row.id;
      obj.goodCode = row.goodCode;
      obj.goodName = row.goodName;
      obj.goldAmount = row.goodAmount * row.goldBean;
      obj.goodAmount = row.goodAmount;
      obj.remark = "";
      this.dataSaleItemList.push(obj);
    },
    /** 选择商品 */
    closeGood() {
      this.goodOpen = false
    },
    /** 查询订单信息列表 */
    getList() {
      this.loading = true;
      listSale(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.saleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 通用排序 */
    tableSortChange(column) {
      this.queryParams.pageNum = 1
      if (column.order === 'descending') {
        this.queryParams.orderByColumn = column.prop
        this.queryParams.isAsc = 'desc'
      } else if (column.order === 'ascending') {
        this.queryParams.orderByColumn = column.prop
        this.queryParams.isAsc = 'asc'
      } else {
        this.queryParams.orderByColumn = undefined
        this.queryParams.isAsc = undefined
      }
      this.getList()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        billNumber: null,
        deptId: null,
        userId: null,
        nickName: null,
        stockUserId: null,
        stockNickName: null,
        allGold: null,
        addUser: null,
        allAmount: null,
        examStatus: 'N',
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.dataSaleItemList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [parseTime(new Date().setDate(1), '{y}-{m}-{d}'), parseTime(new Date(), '{y}-{m}-{d}')]
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSale(id).then(response => {
        this.form = response.data;
        this.dataSaleItemList = response.data.dataSaleItemList;
        this.open = true;
        this.title = "修改订单信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.dataSaleItemList.length == 0) {
            this.$modal.msgWarning("无明细不可提交");
            return;
          }
          this.form.dataSaleItemList = this.dataSaleItemList;
          if (this.form.id != null) {
            updateSale(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSale(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除订单信息编号为"' + ids + '"的数据项？').then(function () {
        return delSale(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 订单明细序号 */
    rowDataSaleItemIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 订单明细添加按钮操作 */
    handleAddDataSaleItem() {
      let obj = {};
      obj.goodId = "";
      obj.goodCode = "";
      obj.goodName = "";
      obj.goldAmount = "";
      obj.goodAmount = "";
      obj.remark = "";
      this.dataSaleItemList.push(obj);
    },
    /** 订单明细删除按钮操作 */
    handleDeleteDataSaleItem() {
      if (this.checkedDataSaleItem.length == 0) {
        this.$modal.msgError("请先选择要删除的订单明细数据");
      } else {
        const dataSaleItemList = this.dataSaleItemList;
        const checkedDataSaleItem = this.checkedDataSaleItem;
        this.dataSaleItemList = dataSaleItemList.filter(function (item) {
          return checkedDataSaleItem.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleDataSaleItemSelectionChange(selection) {
      this.checkedDataSaleItem = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('data/sale/export', {
        ...this.queryParams
      }, `sale_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
